package com.module.overview.ui.widget;

import java.util.TimerTask;

/**
 * 滚动惯性的实现 for HorizontalWheelView
 */
public final class HorizontalInertiaTimerTask extends TimerTask {

    private float mCurrentVelocityX;
    private final float mFirstVelocityX;
    private final HorizontalWheelView mWheelView;

    public HorizontalInertiaTimerTask(HorizontalWheelView wheelView, float velocityX) {
        super();
        this.mWheelView = wheelView;
        this.mFirstVelocityX = velocityX;
        mCurrentVelocityX = Integer.MAX_VALUE;
    }

    @Override
    public final void run() {
        if (mCurrentVelocityX == Integer.MAX_VALUE) {
            if (Math.abs(mFirstVelocityX) > 2000F) {
                mCurrentVelocityX = mFirstVelocityX > 0 ? 2000F : -2000F;
            } else {
                mCurrentVelocityX = mFirstVelocityX;
            }
        }
        if (Math.abs(mCurrentVelocityX) >= 0.0F && Math.abs(mCurrentVelocityX) <= 20F) {
            mWheelView.cancelFuture();
            mWheelView.getHandler().sendEmptyMessage(HorizontalMessageHandler.WHAT_SMOOTH_SCROLL);
            return;
        }
        int dx = (int) (mCurrentVelocityX / 100F);
        mWheelView.setTotalScrollX(mWheelView.getTotalScrollX() - dx);
        if (!mWheelView.isLoop()) {
            float itemWidth = mWheelView.getItemWidth();
            float left = (-mWheelView.getInitPosition()) * itemWidth;
            float right = (mWheelView.getItemsCount() - 1 - mWheelView.getInitPosition()) * itemWidth;
            if (mWheelView.getTotalScrollX() - itemWidth * 0.25 < left) {
                left = mWheelView.getTotalScrollX() + dx;
            } else if (mWheelView.getTotalScrollX() + itemWidth * 0.25 > right) {
                right = mWheelView.getTotalScrollX() + dx;
            }
            if (mWheelView.getTotalScrollX() <= left) {
                mCurrentVelocityX = 40F;
                mWheelView.setTotalScrollX((int) left);
            } else if (mWheelView.getTotalScrollX() >= right) {
                mWheelView.setTotalScrollX((int) right);
                mCurrentVelocityX = -40F;
            }
        }
        if (mCurrentVelocityX < 0.0F) {
            mCurrentVelocityX = mCurrentVelocityX + 20F;
        } else {
            mCurrentVelocityX = mCurrentVelocityX - 20F;
        }
        mWheelView.getHandler().sendEmptyMessage(HorizontalMessageHandler.WHAT_INVALIDATE_LOOP_VIEW);
    }
} 